<template>
  <a-card title="右键操作节点">
    <div slot="extra" class="drawer-bootom-button">
      <a-dropdown :trigger="['click']" placement="topCenter">
        <a-menu slot="overlay">
          <a-menu-item key="4" @click="handleAdd('root')">添加根节点</a-menu-item>
          <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
          <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
        </a-menu>
        <a-button>
          树操作
          <a-icon type="up"/>
        </a-button>
      </a-dropdown>
    </div>
    <div style="background: #fff;">
      <a-col :md="10" :sm="24">
        <template>
          <a-dropdown :trigger="[this.dropTrigger]" @visibleChange="dropStatus">
            <span style="user-select: none">
              <a-tree
                :showIcon="true"
                :icon="getIcon"
                @select="onSelect"
                @check="onCheck"
                @rightClick="rightHandle"
                :selectedKeys="selectedKeys"
                :checkedKeys="checkedKeys"
                :treeData="departTree"
                :checkStrictly="checkStrictly"
                :expandedKeys="iExpandedKeys"
                :autoExpandParent="autoExpandParent"
                @expand="onExpand">
                 <template #title="item">
                  <span v-if="item.type=='position'" style="color:#136030">{{item.title}}</span>
                  <span v-else style="color:#136030">{{item.title}}</span>
                </template>
              </a-tree>
             </span>
            <!--新增右键点击事件,和增加添加和删除功能-->
            <a-menu slot="overlay">
              <a-menu-item @click="handleAdd()" key="1">添加节点</a-menu-item>
              <a-menu-item @click="handleEdit" key="2">编辑节点</a-menu-item>
              <a-menu-item @click="handleDelete" key="3">删除节点</a-menu-item>
              <a-menu-item @click="closeDrop" key="4">取消操作</a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>
      </a-col>
    </div>
    <addTreeNode ref="addTreeNode" @ok="loadTree" :templateId="templateId" :rowData="model"></addTreeNode>
  </a-card>
</template>

<script>
  import {deleteAction, getAction} from '@/api/manage'
  import {JeecgListMixin} from '@/mixins/JeecgListMixin'
  import addTreeNode from "./addTreeNode";

  export default {
    name: "LeftTree",
    props: ['templateId', 'model', 'historyTemplateId', 'proId'],
    mixins: [JeecgListMixin],
    components: {addTreeNode},
    data() {
      return {
        rightClickSelectedKey: '',
        rightClickSelectedNode: '',
        dropTrigger: '',
        iExpandedKeys: [],
        loading: false,
        autoExpandParent: true,
        currFlowId: '',
        currFlowName: '',
        treeData: [],
        departTree: [],
        hiding: true,
        checkedKeys: [],
        selectedKeys: [],
        currSelected: {},
        allTreeKeys: [],
        checkStrictly: true,
        url: '/sjxmzygl/sjWorkZtfa/getTemplateTreeDeptOrFaById',
        orgCategoryDisabled: false,
      }
    },
    computed: {},
    watch: {},
    mounted() {
      console.log('temp', this.templateId);
      console.log('his', this.historyTemplateId);
    },
    methods: {
      getIcon(props) {
        if (props.add) {
          return <a-icon type="form" style="color:#14c996"/>;
        } else {
          return <a-icon type="file"/>;
        }
      },
      loadData() {
        this.refresh();
      },
      handleAdd(root) {
        if (root === 'root') {
          this.$refs.addTreeNode.add('root')
        } else {
          this.$refs.addTreeNode.add(this.rightClickSelectedNode)
        }
      },
      handleEdit() {
        this.$refs.addTreeNode.edit(this.rightClickSelectedNode)
      },
      handleDelete() {
        this.$confirm({
          title: '确认删除',
          content: '确定要删除此部门以及子节点数据吗?',
          onOk: () => {
            deleteAction('/sjxmzygl/sjProjectTemplateTreeFa/updDelFlagById', {id: this.rightClickSelectedNode.jid}).then((res) => {
              if (res.success) {
                this.$message.success('删除成功!')
                this.loadTree()
              }
            })
          }
        })
      },
      // 右键点击下拉框改变事件
      dropStatus(visible) {
        if (visible == false) {
          this.dropTrigger = ''
        }
      },
      // 右键下拉关闭下拉框
      closeDrop() {
        this.dropTrigger = ''
      },
      rightHandle(node) {
        this.dropTrigger = 'contextmenu'
        console.log(node.node.eventKey)
        this.rightClickSelectedKey = node.node.eventKey
        this.rightClickSelectedNode = node.node.dataRef
      },
      loadTree() {
        var that = this
        that.treeData = []
        that.departTree = []
        console.log('his', this.historyTemplateId);
        console.log('temp', this.templateId);
        getAction(this.url, {
          id: this.historyTemplateId || '',
          proId: this.proId,
          templateId: this.templateId,
          ztfaId: this.model.id
        }).then((res) => {
          if (res.success) {
            //部门全选后，再添加部门，选中数量增多
            this.allTreeKeys = [];
            for (let i = 0; i < res.result.length; i++) {
              let temp = res.result[i]
              that.treeData.push(temp)
              that.departTree.push(temp)
              that.setThisExpandedKeys(temp)
              that.getAllKeys(temp);
              // console.log(temp.id)
            }
            this.loading = false
          }
        })
      },
      setThisExpandedKeys(node) {
        if (node.children && node.children.length > 0) {
          this.iExpandedKeys.push(node.key)
          for (let a = 0; a < node.children.length; a++) {
            this.setThisExpandedKeys(node.children[a])
          }
        }
      },
      refresh() {
        this.loading = true
        this.loadTree()
      },
      onExpand(expandedKeys) {
        console.log('onExpand', expandedKeys)
        this.iExpandedKeys = expandedKeys
        this.autoExpandParent = false
      },
      nodeModalOk() {
        this.loadTree()
      },
      nodeModalClose() {
      },
      onCheck(checkedKeys, info) {
        console.log('onCheck', checkedKeys, info)
        this.hiding = false
        //---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------
        if (this.checkStrictly) {
          this.checkedKeys = checkedKeys.checked;
        } else {
          this.checkedKeys = checkedKeys
        }
        //---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------
      },
      treeFindPath(tree, ID) {
        var path = [];
        if (!tree) return [];
        var forFn = function (tree, ID) {
          for (var i = 0; i < tree.length; i++) {
            // 存放最后返回的内容,返回text集合
            var data = tree[i];
            path.push(data);
            if (data.id === ID) return path;
            if (data.children) {
              const findChildren = forFn(data.children, ID);
              if (findChildren) return findChildren;
            }
            path.pop();
          }
        };
        forFn(tree, ID);
        return path;
      },
      onSelect(selectedKeys, e) {
        e.node.dataRef['add'] = true
        let path = this.treeFindPath(this.departTree, selectedKeys[0])
        this.hiding = false
        let record = e.node.dataRef
        this.currSelected = Object.assign({}, record)
        this.selectedKeys = [record.key]
        this.$emit('selected', this.currSelected, path)
      },
      getCurrSelectedTitle() {
        return !this.currSelected.title ? '' : this.currSelected.title
      },
      onClearSelected() {
        this.hiding = true
        this.checkedKeys = []
        this.currSelected = {}
        this.selectedKeys = []
        this.$refs.departAuth.departId = ''
      },
      //---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------
      expandAll() {
        this.iExpandedKeys = this.allTreeKeys
      },
      closeAll() {
        this.iExpandedKeys = []
      },
      getAllKeys(node) {
        // console.log('node',node);
        this.allTreeKeys.push(node.key)
        if (node.children && node.children.length > 0) {
          for (let a = 0; a < node.children.length; a++) {
            this.getAllKeys(node.children[a])
          }
        }
      }
      //---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------
    },
    created() {
    },
  }
</script>

<style lang="less" scoped>
  .ant-card {
    height: 100%;

    /deep/ .ant-card-head {
      padding: 0 15px;

      /deep/ .ant-card-head-title, /deep/ .ant-card-extra {
        padding: 10px 0;
      }
    }

    /deep/ .ant-card-body {
      color: #14c996;
      padding: 10px;
      height: calc(100vh - 450px);
      overflow: auto;
    }
  }
</style>